package com.yangyang.androidconnect.mdns;

import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.util.Log;

public class NsdHelper {
    private NsdManager nsdManager;
    private NsdManager.RegistrationListener registrationListener;
    private String serviceName = "Android Connect";
    // 标准 HTTP 服务  "_http._tcp.local."

    public NsdHelper(NsdManager nsdManager) {
        this.nsdManager = nsdManager;
    }

    public void registerService(int port) {
        // 创建服务信息
        NsdServiceInfo serviceInfo = new NsdServiceInfo();
        serviceInfo.setServiceName(serviceName);
        serviceInfo.setServiceType("_http._tcp.");
        //.setServiceType(SERVICE_TYPE_HTTP);
        serviceInfo.setPort(port);

        // 创建注册监听器
        registrationListener = new NsdManager.RegistrationListener() {
            @Override
            public void onServiceRegistered(NsdServiceInfo serviceInfo) {
                serviceName = serviceInfo.getServiceName();
                Log.d("NSD", "服务注册成功: " + serviceName);
            }
            
            @Override
            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.e("NSD", "服务注册失败, 错误码: " + errorCode);
            }
            
            @Override
            public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
                Log.d("NSD", "服务取消注册: " + serviceInfo.getServiceName());
            }
            
            @Override
            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                Log.e("NSD", "服务取消注册失败, 错误码: " + errorCode);
            }
        };
        
        // 注册服务
        nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener);
    }
    
    public void unregisterService() {
        if (nsdManager != null && registrationListener != null) {
            nsdManager.unregisterService(registrationListener);
        }
    }
}